import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an8 from '@mmstudio/an000008';
import an48 from '@mmstudio/an000048';
import { tbfdmenu } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/menu/add.api');

export type Result = {
	ok: true;
	id: string;
} | {
	ok: false;
	message: string;
};

export type Message = Pick<ITbfdmenu, 'pid' | 'name'>;

/**
 * 新增菜单
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;

		if (!body
			|| !body.name
		) {
			res.status(200).json({
				ok: false,
				message: '菜单名称不能为空'
			});
			return;
		}
		const r = await tbfdmenu().first('*').where({
			name: body.name,
		});
		if (r) {
			res.status(200).json({ ok: false, message: '该菜单已存在' });
			return;
		}
		const id = an8();
		await tbfdmenu().insert({
			...body,
			menuid: id
		});
		res.status(200).json({
			ok: true,
			id
		});
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
